package com.ball.dev.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ball.common.dtos.ResponseResult;
import com.ball.common.utils.AppJwtUtil;
import com.ball.dev.entity.po.AppUser;
import com.ball.dev.service.IAppUserService;
import com.ball.dev.service.WeChatAuthService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WeChatAuthServiceImpl implements WeChatAuthService {

    private  String appId;
    private  String appSecret;

    @Autowired
   private IAppUserService userService;
    public WeChatAuthServiceImpl(@Value("${wechat.app-id}") String appId,
                              @Value("${wechat.app-secret}") String appSecret) {
        this.appId = appId;
        this.appSecret = appSecret;
    }

    public ResponseResult login(String jsCode) {
        // 调用微信接口获取openid和session_key
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session"
                           + "?appid=" + appId
                           + "&secret=" + appSecret
                           + "&js_code=" + jsCode
                           + "&grant_type=authorization_code";

        // 发送HTTP请求并解析响应内容
        // 这里假设使用了RestTemplate或者OkHttp之类的工具类
//        ResponseEntity<String> response = restTemplate.getForEntity(requestUrl, String.class);
        String body = HttpRequest.get(requestUrl).execute().body();

        // 解析响应json，获取openid等信息
        JSONObject jsonObject = JSON.parseObject(body);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");

        // 使用openid关联或创建用户，然后生成并返回token
        AppUser user = userService.lambdaQuery().eq(AppUser::getOpenid,openid)
                .eq(AppUser::getStatus,0).one(); // 假设有一个服务方法用来获取或创建用户

        if (user == null) {
            // 添加用户
            AppUser appUser = new AppUser();
            appUser.setOpenid(openid);

            // 记录用户的登录态

        }


        String token = AppJwtUtil.getToken(user.getId());// 生成JWT令牌

        return ResponseResult.okResult(token);
    }


}